package com.yinhai.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.lz.util.Utils;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.CheckUserInfoTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.cfg.AppConfig;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.OnlineContactDetail;
import com.yinhai.service.ContactUserServiceImpl;

/**
 * @author Juyon
 * 
 */
public class OnlineContactDetailFragment extends Fragment {
    
    LinearLayout li;
    
    public String phone, shortphone, officephone;
    
    private ImageView btn_back;
    
    private AQuery aq = null;
    
    private View layout_chat, layout_share, layout_check;
    
    OnlineContactDetail detail;
    
    String userId;
    
    EditText addEditText;
    
    String add_title, selfphone;
    
    private Context tt = null;
    
    private String parentIds = "";
    
    private String clickId = "";
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.online_contact_item_detail, null);
        tt = getActivity();
        Bundle bundle = this.getArguments();
        userId = bundle.getString("userId");
        clickId = bundle.getString("clickId");
        parentIds = bundle.getString("parentIds");
        aq = new AQuery(getActivity(), view);
        SharedPreferences preferences = tt.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
        selfphone = preferences.getString("name", "");
        ContactUserServiceImpl userService = new ContactUserServiceImpl(this.getActivity());
        detail = userService.findOnlineContactDetail(userId);
        initData(detail, view);
        
        btn_back = (ImageView)view.findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                // Fragment fragment = new ContactNewFragment();
                Fragment fragment = new ContactGroupFragment();
                Bundle bundle = new Bundle();
                bundle.putString("parentIds", parentIds);
                bundle.putString("clickId", clickId);
                fragment.setArguments(bundle);
                transaction.replace(R.id.container, fragment);
                transaction.commit();
            }
        });
        layout_chat = (View)view.findViewById(R.id.layout_chat);
        layout_share = (View)view.findViewById(R.id.layout_share);
        layout_check = (View)view.findViewById(R.id.layout_check);
        layout_chat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra("receID", phone);
                intent.putExtra("receName", detail.getName());
                intent.putExtra("type", 1);
                getActivity().startActivity(intent);
            }
        });
        layout_share.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String body = "姓名：" + detail.getName() + "\n电话号码：" + phone;
                Uri smsToUri = Uri.parse("smsto:");// 联系人地址
                Intent mIntent = new Intent(android.content.Intent.ACTION_SENDTO, smsToUri);
                mIntent.putExtra("sms_body", body);// 短信内容
                startActivity(mIntent);
            }
        });
        layout_check.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                LayoutInflater factory = LayoutInflater.from(tt);
                final View addEntryView = factory.inflate(R.layout.dialog_checknote, null);
                addEditText = (EditText)addEntryView.findViewById(R.id.sort_edit);
                
                AlertDialog dlg =
                    new AlertDialog.Builder(tt).setIcon(0)
                        .setTitle("信息纠错")
                        .setView(addEntryView)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                add_title = addEditText.getText().toString().trim();
                                if (add_title.equals("")) {
                                    Toast.makeText(tt, "纠错信息不能为空!", Toast.LENGTH_SHORT).show();
                                } else {
                                    CheckUserInfoTask backupCloudNoteTask = new CheckUserInfoTask(tt);
                                    AsyncTaskParam taskParam =
                                        new AsyncTaskParam(UrlConstant.LOCAL_URI + UrlConstant.CORRECT_CONTACT);
                                    List<NameValuePair> postParam = new ArrayList<NameValuePair>();
                                    NameValueParam nvp = new NameValueParam();
                                    nvp.setName("sendUserPhone");
                                    nvp.setValue(selfphone);
                                    postParam.add(nvp);
                                    
                                    nvp = new NameValueParam();
                                    nvp.setName("errorUserPhone");
                                    nvp.setValue(phone);
                                    postParam.add(nvp);
                                    
                                    nvp = new NameValueParam();
                                    nvp.setName("desc");
                                    nvp.setValue(add_title);
                                    postParam.add(nvp);
                                    
                                    taskParam.setPostParam(postParam);
                                    backupCloudNoteTask.execute(taskParam);
                                    
                                }
                                
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.dismiss();
                            }
                        })
                        .create();
                dlg.show();
            }
        });
        aq.id(R.id.layout_cont).tag("1").clicked(onClick);
        aq.id(R.id.layout_id).tag("2").clicked(onClick);
        aq.id(R.id.layout_shortphone).tag("3").clicked(onClick);
        aq.id(R.id.detail_mobile).tag("4").clicked(onClick);
        return view;
    }
    
    OnClickListener onClick = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String n = v.getTag().toString();
            if (n.equals("1")) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                
                getActivity().startActivity(intent);
            } else if (n.equals("2")) {
                String telNo = phone;
                Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + telNo));
                getActivity().startActivity(sendIntent);
            } else if (n.equals("3")) {
                if (!shortphone.equals("")) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + shortphone));
                    
                    getActivity().startActivity(intent);
                }
                
            } else if (n.equals("4")) {
                if (!officephone.equals("")) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + officephone));
                    
                    getActivity().startActivity(intent);
                }
                
            } else {
                
            }
            
        }
    };
    
    // 拨号
    private void dial(String telNo) {
        if (telNo != null && telNo.length() > 0) {
            Uri uri = Uri.parse("tel:" + telNo);
            Intent intent = new Intent(Intent.ACTION_CALL, uri);
            getActivity().startActivity(intent);
        }
    }
    
    private void initData(OnlineContactDetail detail, View view) {
        aq.id(R.id.detail_name).text(detail.getName() == null ? "" : detail.getName()
            .replace("null", "")
            .replace("NULL", ""));
        aq.id(R.id.detail_company).text(detail.getCompany() == null ? "" : detail.getCompany()
            .replace("null", "")
            .replace("NULL", ""));
        aq.id(R.id.detail_duty).text(detail.getDuty() == null ? "" : detail.getDuty()
            .replace("null", "")
            .replace("NULL", ""));
        aq.id(R.id.detail_telphone).text(detail.getTelPhone() == null ? "" : detail.getTelPhone()
            .replace("null", "")
            .replace("NULL", ""));
        phone = detail.getTelPhone() == null ? "" : detail.getTelPhone().replace("null", "").replace("NULL", "");
        aq.id(R.id.detail_shortphone).text(detail.getShortPhone() == null ? "" : detail.getShortPhone()
            .replace("null", "")
            .replace("NULL", ""));
        shortphone =
            detail.getShortPhone() == null ? "" : detail.getShortPhone().replace("null", "").replace("NULL", "");
        aq.id(R.id.detail_mobile).text(detail.getMobile() == null ? "" : detail.getMobile()
            .replace("null", "")
            .replace("NULL", ""));
        officephone = detail.getMobile() == null ? "" : detail.getMobile().replace("null", "").replace("NULL", "");
        /*
         * aq.id(R.id.detail_email).text( detail.getEmail() == null ? "" : detail.getEmail() .replace("null",
         * "").replace("NULL", ""));
         */
        aq.id(R.id.img).image(UrlConstant.LOCAL_URI + "getPhoto?phone=" + detail.getTelPhone(),
            Utils.getImageOptions(tt, R.drawable.tel_photo, Utils.IsImgSize));
    }
}
